package com.teemor.open.openauth.validator;


import com.teemor.common.bean.utils.redis.RedisUtils;
import com.teemor.open.openauth.AuthUtils;
import com.teemor.open.openauth.enums.ResultCode;
import com.teemor.open.openauth.model.AuthResource;
import com.teemor.open.openauth.model.AuthUserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import java.util.List;
import java.util.Objects;

/**
 * @ename zhoulk
 * @cname 周李科
 * @date 2020/6/2 14:54
 */
public class AuthValidator implements AuthValid<Boolean, CheckBean> {

    @Autowired
    private RoleValidator<Boolean> roleValidator;


    @Override
    public ResultCode valid(CheckBean check) {
        AuthResource authResource;
        if ((authResource = checkUrl(check.getUrl())) != null) {
            if (check.getToken() == null)  {
                return ResultCode.NOTLOGIN;
            }
            Object object = RedisUtils.getObject(check.getToken());
            if (Objects.isNull(object) || !(object instanceof AuthUserModel)) {
                return ResultCode.TOKEN_EXPIRED;
            }
            AuthUserModel authModel = (AuthUserModel) object;
            Boolean valid = roleValidator.valid(authModel, authResource);
            if (!valid) {
                return ResultCode.NOT_AUTH;
            }
        }
        return ResultCode.SUCCESS;
    }

    private AuthResource checkUrl(String checkUrl) {
        List<AuthResource> authResources = AuthUtils.getCheckResource();
        for (AuthResource url : authResources) {
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            if (antPathMatcher.match(url.getValue(), checkUrl)) return url;
        }
        return null;
    }
}
